<script name='Project' setup>
import {
    queryProjectListApi,
    addProjectApi,
    updateProjectApi,
    delProjectApi,
    queryProjectNameApi,
    updateProjectStatusApi
} from '@/api/business/project'
import { computed, reactive, ref } from 'vue'
import useUserStore from '@/store/modules/user'
import useCommonStore from '@/store/modules/common'
const userStore = useUserStore()
const commonStore = useCommonStore()
const { proxy } = getCurrentInstance()
const { business_project_status } = proxy.useDict('business_project_status')

//查询
const showSearch = ref(true)
const dateRange = ref([])
const queryParams = ref({
    pageNum: 1,
    pageSize: 10,
    projectName: void 0,
    status: void 0,
    leader: [],
    member: []
})
const total = ref(0)

const queryLeaderList = computed(() => commonStore.userList.filter(item => !queryParams.value.member.includes(item.userId)))
const queryMemberList = computed(() => commonStore.userList.filter(item => !queryParams.value.leader.includes(item.userId)))

/** 搜索按钮操作 */
function handleQuery() {
    queryParams.value.pageNum = 1
    let leaderStr = queryParams.value.leader.join(',')
    let memberStr = queryParams.value.member.join(',')
    getList({ ...proxy.addDateRange(queryParams.value, dateRange.value), leader: leaderStr, member: memberStr })
}
/** 重置按钮操作 */
function resetQuery() {
    proxy.resetForm('queryRef')
    dateRange.value = []
    handleQuery()
}

//列表
const loading = ref(false)
const projectList = ref([])
const ids = ref([])
const multiple = ref(true)

/** 查询项目列表 */
async function getList(params) {
    loading.value = true
    const { data } = await queryProjectListApi(params)
    console.log(data, '项目列表')
    projectList.value = data.list
    total.value = data.total
    loading.value = false
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.projectId)
    multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
    reset()
    open.value = true
    title.value = '添加项目'
}

/** 修改按钮操作 */
function handleUpdate(row) {
    reset()
    form.value.projectId = row.projectId
    form.value.projectName = row.projectName
    form.value.leader = row.leader.map(item => item.userId)
    form.value.member = row.member.map(item => item.userId)
    form.value.remark = row.remark
    open.value = true
    title.value = '修改项目'
}

/** 删除按钮操作 */
function handleDelete(row) {
    const projectIds = (row.projectId && [row.projectId]) || ids.value
    const projectNames = projectIds.map(projectId => {
        return projectList.value.find(project => project.projectId == projectId).projectName
    })
    console.log(projectNames, 'ddddddddddddd')

    proxy.$modal.confirm('是否确认删除项目 ' + `${projectNames.join(', ')}`).then(function () {
        return delProjectApi(projectIds)
    }).then(() => {
        handleQuery()
        proxy.$modal.msgSuccess('删除成功')
    }).catch(() => {
    })
}

async function handleUpdateStatus(row, status) {
    await updateProjectStatusApi({ projectId: row.projectId, status })
    handleQuery()
}

//表单
const title = ref('')
const open = ref(false)
const form = ref({
    projectId: void 0,
    projectName: void 0,
    leader: [],
    member: [],
    remark: void 0
})
const rules = ref({
    projectName: [{ required: true, message: '项目名称不能为空', trigger: 'blur' }],
    leader: [{ required: true, message: '岗位编码不能为空', trigger: 'change' }]
})
const formLeaderList = computed(() => commonStore.userList.filter(item => !form.value.member.includes(item.userId)))
const formMemberList = computed(() => commonStore.userList.filter(item => !form.value.leader.includes(item.userId)))

/** 取消按钮 */
function cancel() {
    open.value = false
    reset()
}

/** 表单重置 */
function reset() {
    form.value = {
        projectId: void 0,
        projectName: void 0,
        leader: [],
        member: [],
        remark: void 0
    }
    proxy.resetForm('projectRef')
}

/** 提交按钮 */
function submitForm() {
    proxy.$refs['projectRef'].validate(async valid => {
        if (valid) {
            const { data } = await queryProjectNameApi(form.value.projectName)
            if (data.isRepeat) {
                await proxy.$modal.confirm('当前已有重复的项目名称，是否继续')
            }
            if (form.value.projectId != undefined) {
                updateProjectApi(form.value).then(() => {
                    proxy.$modal.msgSuccess('修改成功')
                    open.value = false
                    handleQuery()
                })
            } else {
                addProjectApi(form.value).then(() => {
                    proxy.$modal.msgSuccess('新增成功')
                    open.value = false
                    handleQuery()
                })
            }

        }
    })
}

handleQuery()
</script>

<template>
    <div class='app-container'>
        <el-form v-show="showSearch" ref="queryRef" :inline="true" :model="queryParams">
            <el-form-item label="项目名称" prop="projectName">
                <el-input v-model="queryParams.projectName" clearable placeholder="请输入项目名称" style="width: 200px"
                    @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="负责人" prop="leader">
                <el-select v-model="queryParams.leader" clearable filterable multiple placeholder="负责人"
                    style="width: 200px">
                    <el-option v-for="item in queryLeaderList" :key="item.userId" :label="item.nickName"
                        :value="item.userId"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="成员" prop="member">
                <el-select v-model="queryParams.member" clearable filterable multiple placeholder="成员"
                    style="width: 200px">
                    <el-option v-for="item in queryMemberList" :key="item.userId" :label="item.nickName"
                        :value="item.userId"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="项目进度" prop="status">
                <el-select v-model="queryParams.status" clearable placeholder="项目进度" style="width: 200px">
                    <el-option v-for="dict in business_project_status" :key="dict.value" :label="dict.label"
                        :value="dict.value" />
                </el-select>
            </el-form-item>
            <el-form-item label="开始时间" style="width: 308px">
                <el-date-picker v-model="dateRange" end-placeholder="结束日期" range-separator="-" start-placeholder="开始日期"
                    type="daterange" value-format="YYYY-MM-DD"></el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-button icon="Search" type="primary" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button v-hasPermi="['business:project:add']" icon="Plus" plain type="primary" @click="handleAdd">新增
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button v-hasPermi="['business:project:remove']" :disabled="multiple" icon="Delete" plain
                    type="danger" @click="handleDelete">删除
                </el-button>
            </el-col>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="handleQuery"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="projectList" @selection-change="handleSelectionChange">
            <el-table-column align="center" type="selection" width="55" />
            <el-table-column align="center" label="项目名称" prop="projectName" />
            <el-table-column align="center" label="负责人" prop="leader">
                <template #default="{ row }">
                    <div style="display: flex;gap: 2%;justify-content: center;align-items: center;">
                        <el-tag v-for="item in row.leader" :key="item.userId" class="mr-2" type="success">{{
                            item.nickName
                            }}
                        </el-tag>
                    </div>
                </template>
            </el-table-column>
            <el-table-column align="center" label="成员" prop="member">
                <template #default="{ row }">
                    <div class="flex-center" style="gap: 2%;">
                        <el-tag v-for="item in row.member" :key="item.userId" class="mr-2">{{ item.nickName
                            }}
                        </el-tag>
                    </div>
                </template>
            </el-table-column>
            <el-table-column align="center" label="进度" prop="status" width="180">
                <template #default="{ row }">
                    <div class="flex-center" style="gap: 4%;">
                        <el-button
                            v-if="row.status !== business_project_status[business_project_status.length - 1]?.value &&
                                row.status !== business_project_status[0]?.value &&
                                row.status !== business_project_status[1]?.value &&
                                (userStore.permissions.includes(`business:project:${row.status}`) || userStore.permissions.includes(`*:*:*`))"
                            circle icon="ArrowLeftBold" size="small"
                            @click="handleUpdateStatus(row, Number(row.status) - 1)" />
                        <dict-tag :options="business_project_status" :value="row.status" />
                        <el-button
                            v-if="row.status !== business_project_status[business_project_status.length - 1]?.value &&
                                (userStore.permissions.includes(`business:project:${row.status}`) || userStore.permissions.includes(`*:*:*`))"
                            circle icon="ArrowRightBold" size="small"
                            @click="handleUpdateStatus(row, Number(row.status) + 1)" />
                    </div>
                </template>
            </el-table-column>
            <el-table-column align="center" label="创建时间" prop="createTime" width="180">
                <template #default="{ row }">
                    <span>{{ parseTime(row.createTime) }}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="开始时间" prop="createTime" width="180">
                <template #default="{ row }">
                    <span>{{ parseTime(row.beginTime) || '- -' }}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="结束时间" prop="createTime" width="180">
                <template #default="{ row }">
                    <span>{{ parseTime(row.endTime) || '- -' }}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" class-name="small-padding fixed-width" label="操作">
                <template #default="{ row }">
                    <el-button v-hasPermi="['business:project:score']" icon="Edit" link type="primary"
                        @click="$router.push(`/business/score/${row.projectId}`)">量化分
                    </el-button>
                    <el-button v-hasPermi="['business:project:edit']" icon="Edit" link type="primary"
                        @click="handleUpdate(row)">修改
                    </el-button>
                    <el-button v-hasPermi="['business:project:remove']" icon="Delete" link type="primary"
                        @click="handleDelete(row)">删除
                    </el-button>
                    <el-button v-hasPermi="['business:project:annex']" icon="Document" link type="primary"
                        @click="$router.push(`/business/annex/${row.projectId}`)">附件
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNum"
            :total="total" @pagination="getList" />

        <!-- 添加或修改项目对话框 -->
        <el-dialog v-model="open" :title="title" append-to-body width="500px">
            <el-form ref="projectRef" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="项目名称" prop="projectName">
                    <el-input v-model="form.projectName" placeholder="请输入项目名称" />
                </el-form-item>
                <el-form-item label="负责人" prop="leader">
                    <el-select v-model="form.leader" filterable multiple placeholder="请选择负责人">
                        <el-option v-for="item in formLeaderList" :key="item.userId" :label="item.nickName"
                            :value="item.userId"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="项目成员" prop="member">
                    <el-select v-model="form.member" filterable multiple placeholder="请选择成员">
                        <el-option v-for="item in formMemberList" :key="item.userId" :label="item.nickName"
                            :value="item.userId"></el-option>
                    </el-select>
                </el-form-item>
                <!-- <el-form-item label="项目" prop="status">
            <el-radio-group v-model="form.status">
                <el-radio v-for="dict in business_project_status" :key="dict.value" :value="dict.value">{{
                    dict.label
                }}</el-radio>
            </el-radio-group>
        </el-form-item> -->
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="form.remark" placeholder="请输入内容" type="textarea" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<style lang='scss' scoped>
.flex-center {
    display: flex;
    justify-content: center;
    align-items: center;
}
</style>
